package service

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"CHATROOM/model"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

type User struct {
	Username string          `json:"username"`
	Rooms    string          `json:"rooms"`
	Conn     *websocket.Conn `json:"conn"`
}

// 登录
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "用户名或密码不能为空",
		})
		return
	}
	// 判断账号是否唯一
	cnt, _ := model.GetUserBasicByUsername(username, password)
	if cnt == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名or密码不正确",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
	}
}

// 注册
func Register(c *gin.Context) {
	username := c.PostForm("username") //用户名
	password := c.PostForm("password") //密码
	code := c.PostForm("code")         //邀请码
	fmt.Println("register:", username, password, code)
	if code == "" || username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "缺少参数",
		})
		return
	} else if code != "616game" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "邀请码错误",
		})
		return
	}
	// 判断账号是否唯一
	cnt, err := model.GetUserBasicByUsername(username, password)
	if err != nil {
		log.Printf("[DB ERROR]:%v\n", err)
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "系统错误",
		})
		return
	}

	if cnt != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户已存在",
		})
		return
	} else {
		ub := &model.UserBasic{
			Username:  username,
			Password:  password,
			CreatedAt: time.Now().Unix(),
			UpdatedAt: time.Now().Unix(),
		}
		err = model.InsertUserBasicByUsername(ub)
		if err != nil {
			log.Printf("[DB ERROR]:%v\n", err)
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  "系统错误",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
	}
}
